import axios from 'axios'
import store from '../store'
import { ElMessage } from 'element-plus'
import { diffTokenTime } from './auth'
const server = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

server.interceptors.request.use(config => {
  const token = store.getters.token
  if (token) {
    if (diffTokenTime()) {
      store.dispatch('app/logout')
      return Promise.reject(new Error('token 失效了'))
    }
    config.headers.Authorization = token
  }
  return config
}, err => {
  return Promise.reject(new Error(err))
})

server.interceptors.response.use(config => {
  const { data, meta } = config.data
  if (meta.status === 200 || meta.status === 201) {
    return data
  } else {
    ElMessage.error(meta.msg)
    return Promise.reject(new Error(meta.msg))
  }
}, error => {
  error.response && ElMessage.error(error.response.data)
  return Promise.reject(new Error(error.response.data))
})

export default server
